package com.oocl.tm.service.impl;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.HashMap;

import com.oocl.tm.dao.ClientsDao;
import com.oocl.tm.dao.impl.ClientsDaoImpl;
import com.oocl.tm.log4j.Log4j;
import com.oocl.tm.protocol.MsgPackage;
import com.oocl.tm.protocol.Operation;
import com.oocl.tm.repository.ClientsDBFactory;
import com.oocl.tm.service.ExitService;
import com.oocl.tm.util.JsonUtil;

public class ExitServiceImpl implements ExitService{

	private MsgPackage msgPackage;
	private OutputStream out;
	private ClientsDao dao;
	
	public ExitServiceImpl(MsgPackage msgPackage, OutputStream out) {
		this.msgPackage = msgPackage;
		this.out = out;
		dao = new ClientsDaoImpl();
	}

	@Override
	public void delOneOutput() {
		dao.delAnOutput(msgPackage.getSender());
	}

	@Override
	public void refreshOffline() {
		dao.refreshOffline(msgPackage.getSender());
	}

	@Override
	public void noticeOnline() {
		
		HashMap<String, Boolean> clientList = new HashMap<String, Boolean>();
		for(String name:ClientsDBFactory.getClientsList().keySet()){
			clientList.put(name, ClientsDBFactory.getClientsList().get(name));
		}
		
		MsgPackage msgPackage =new MsgPackage(Operation.NOTIFY, null, null, null, null, clientList);
		Log4j.getLogger().info("[ One client left, Latest online to all ] "+msgPackage.toString());
		for (String name : clientList.keySet()) {
			if(clientList.get(name)){
				try {
					out = ClientsDBFactory.getOutputsList().get(name);
					String  json = JsonUtil.parserToString(msgPackage);
					out.write(json.getBytes());
				} catch (IOException e) {
					Log4j.getLogger().error("[ one client exit caused this exception ]");
					Log4j.getLogger().error(e, e.fillInStackTrace());
				}
			}
		}
		
	}

}
